<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$shopid=$_GPC['shopid'];
$userid=$_GPC['juserid'];
if(!$userid || !$shopid){
	$operation="login";
	include $this->template('default/'.$cfg['floder'].'/phone');
	exit();
}
$userOper=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and id=:a limit 1",array(":a"=>$userid));
if(!$userOper)message("用户不存在或者密码错误",$this->createMobileUrl('phone',array('op'=>'login')),"error");
if(!$userOper['status'])message("该用户还没有审核，请联系管理员",$this->createMobileUrl('phone',array('op'=>'login')),"error");
$shopid=$userOper['pcate'];
$shop=pdo_fetch("SELECT * FROM " . tablename('j_hmoney_group') . " WHERE id =:a",array(":a"=>$shopid));
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
load()->model('mc');

if ($operation == 'display') {
	$tablepcatelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_tablecategory') . " WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' order by displayorder asc,id desc");
	$categoryary=array();
	foreach($tablepcatelist as $row){
		$categoryary[$row['id']]=$row['title'];
	}
	$goodpcatelist = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goodcategory') . " WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' order by  displayorder asc, id desc");
	$isNoPcate=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_goods')." WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' and pcate=0");
	$isfungood=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_goodmarket')." WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' and status=1 and starttime<='".TIMESTAMP."' and endtime>='".TIMESTAMP."' and contentid<>'' ");
	
}elseif ($operation == 'logout') {	
	isetcookie('juserid',"",-1);
	isetcookie('shopid',"",-1);
	isetcookie('shortpass',"",-1);
	isetcookie('selfttableid',"",-1);
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'startorder') {
	$tid=intval($_GPC['tid']);
	$person=intval($_GPC['person']);
	if(!$tid)die(json_encode(array("success"=>false,'msg'=>'请选择餐桌')));
	$table = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE id=:a ",array(":a"=>$tid));
	isetcookie('selfttableid', $tid);
	if($table['status']==0){
		$orderDisplayorder=pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_order') . " WHERE weid='".$_W['uniacid']."' and groupid=:a and createdate=:b ",array(":a"=>$tid,":b"=>date("Y-m-d")));
		$data=array(
			"weid"=>$_W['uniacid'],
			"groupid"=>$shopid,
			"userid"=>$userid,
			"serialnum"=>$orderDisplayorder+1,
			"out_trade_no"=>TIMESTAMP.mt_rand(100,999),
			"tableid"=>$tid,
			"person"=>$person,
			"teafee"=>intval(($person*$table['perperson']+$table['teafee'])*100),
			"createtime"=>TIMESTAMP,
			"createdate"=>date("Y-m-d"),
		);
		pdo_insert("j_hmoney_order",$data);
		$orderid=pdo_insertid();
		pdo_update('j_hmoney_table',array("status"=>1,"createtime"=>TIMESTAMP),array("id"=>$tid));
		$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
		die(json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade)));
		
	}elseif($table['status']==1){
		
		$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and tableid=:a order by id desc limit 1",array(":a"=>$tid));
		if($orderid)$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
		$goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));
		die(json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade,'goods'=>$goodlist)));
		
	}elseif($table['status']==2){
		
		$tradelist=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and tableid=:a and status<2 order by id desc  ",array(":a"=>$tid));
		if(count($tradelist)==1){
			$trade=$tradelist[0];
			$goodlist=pdo_fetchall("SELECT a.*,b.title,b.memberprice,b.unitname,b.marketprice FROM ".tablename('j_hmoney_ordergoods')." as a LEFT JOIN ".tablename('j_hmoney_goods')." as b ON a.goodid=b.id  WHERE a.out_trade_no=:a order by a.id desc ",array(":a"=>$trade['out_trade_no']));
			die(json_encode(array('success'=>true,'table'=>$table,'trade'=>$trade,'goods'=>$goodlist)));
		}else{
			die(json_encode(array('success'=>true,'table'=>$table,'tradelist'=>$tradelist)));
		}
	}
	die(json_encode(array("success"=>true)));
	
} elseif ($operation == 'getpcatetable') {
	$pcate=intval($_GPC['pcate']);
	if(!$pcate){
		$pcate = pdo_fetchcolumn("SELECT id FROM " . tablename('j_hmoney_tablecategory') . " WHERE weid = '".$_W['uniacid']."' and groupid ='".$shopid."' order by displayorder asc,id desc limit 1");
	}
	$tablelist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_table') . " WHERE weid = '".$_W['uniacid']."' and pcate=:a order by status desc ,displayorder asc,id asc",array(":a"=>$pcate));
	die(json_encode(array('success'=>true,'list'=>$tablelist)));
	
} elseif ($operation == 'getpcategood') {
	$pcate=intval($_GPC['pcate']);
	$goodslist=array();
	if($pcate==-1){
		$list=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goodmarket') . " WHERE groupid=:a and status=1 and starttime<=:b and endtime>=:b and contentid<>'' order by id desc",array(":a"=>$shopid,":b"=>TIMESTAMP));
		foreach($list as $row){
			if($row['limitweek']){
				$day=date('w') ? date('w') : 7;
				if(!in_array($day,explode(',',$row['limitweek'])))continue;
			}
			if($row['limithour']){
				$time=intval(date('h'));
				if(!in_array($time,explode(',',$row['limithour'])))continue;
			}
			$goods=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_goods')." WHERE id in(".$row['contentid'].") and status=1 and store<>0 order by id desc");
			for($i=0;$i<count($goods);$i++){
				$temp=$goods[$i];
				if(strpos($row['discount'],"%")){
					$temp['title2']=(str_replace("%","",$row['discount'])*0.1)."折";
					$temp['marketprice']=$this->_2money($goods[$i]['marketprice']*(str_replace("%","",$row['discount'])));
				}
				if(strpos($row['discount'],"-")!==false){
					if($goods[$i]['marketprice']-abs($row['discount'])>=0){
						$temp['title2']=(str_replace("-","立减",$row['discount']));
						$temp['marketprice']=$this->_2money(($goods[$i]['marketprice']-abs($row['discount'])));
					}
					
				}
				array_push($goodslist,$temp);
			}
		}
	}else{
		$goodslist=pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_goods') . " WHERE weid = '".$_W['uniacid']."' and pcate=:a and groupid=:b and status=1 and store<>0 order by displayorder asc,id asc",array(":a"=>$pcate,":b"=>$shopid));
	}
	for($i=0;$i<count($goodslist);$i++){
		if(!$goodslist[$i]['thumb'])continue;
		$goodslist[$i]['thumb']=tomedia($goodslist[$i]['thumb']);
	}
	die(json_encode(array('success'=>true,'list'=>$goodslist,"a"=>count($goods))));

} elseif ($operation == 'submitorder') {
	$orderid=$_GPC["orderid"];
	$person=$_GPC["person"];
	$param=$_GPC["param"];
	if(!$orderid)die(json_encode(array('success'=>false,'msg'=>"订单编号不能为空")));
	$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$orderid));
	$table=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_table')." WHERE weid = '".$_W['uniacid']."' and id=:a ",array(":a"=>$trade['tableid']));
	$sqlinsert="insert into ".tablename('j_hmoney_ordergoods')." (weid,groupid,orderid,out_trade_no,createtime,status,goodid,goodsn,title,price,oldprice,num,total_fee,ispack,taste)VALUES";
	$newgoodAry=array();
	$tempInsertAry=array();
	$isallnew=true;
	foreach($param as $row){
		//id+"|"+goodid+"|"+goodsn+"|"+title+"|"+price+"|"+mprice+"|"+oprice+"|"+num+"|"+fee+ispack+taste
		$tempAry=explode("|",$row);
		
		if(!$tempAry[0]){
			if(!isset($newgoodAry[$tempAry[1]]))$newgoodAry[$tempAry[1]]=0;
			$newgoodAry[$tempAry[1]]=$newgoodAry[$tempAry[1]]+$tempAry[7];
			$temp=array($_W["uniacid"],$shopid,$orderid,$trade['out_trade_no'],TIMESTAMP,1,$tempAry[1],$tempAry[2],$tempAry[3],$tempAry[4],$tempAry[6],$tempAry[7],intval($tempAry[8]*100),intval($tempAry[9]),$tempAry[10]);
			$tempInsertAry[]="('".implode("','",$temp)."')";
		}else{
			$isallnew=false;
			$temp=array(
				"price"=>$tempAry[4],
				"fee"=>intval($tempAry[8]*100),
				"ispack"=>$tempAry[9],
				"taste"=>$tempAry[10]
			);
			pdo_update("j_hmoney_ordergoods",$temp,array("id"=>$tempAry[0]));
		}
	}
	//--计算数量--//
	if(count($newgoodAry)){
		$goodataAry=array();
		$goodsql="UPDATE ".tablename('j_hmoney_goods')." SET store = CASE id ";
		$goodlist=pdo_fetchall("SELECT id,store,title FROM ".tablename('j_hmoney_goods')." WHERE id in (".implode(",",array_keys($newgoodAry)).") and store>-1 ");
		foreach($goodlist as $row){
			if($row['store']-$newgoodAry[$row['id']]<0){
				die(json_encode(array('success'=>false,'msg'=>"【".$row['title']."】库存不足,差【".abs($row['store']-$newgoodAry[$row['id']])."】份")));
				break;
			}
			$goodsql.=" WHEN ".$row['id']." THEN ". ($row['store']-$newgoodAry[$row['id']]);
		}
		$goodsql.="END WHERE id IN (".implode(",",array_keys($newgoodAry)).")";
		$sql=$sqlinsert.implode(",",$tempInsertAry).";".$goodsql;
		pdo_run($sql);
	}
	pdo_update("j_hmoney_table",array("status"=>2),array("id"=>$trade['tableid']));
	$gather=pdo_fetch("SELECT sum(num) as num1,count(*) as num2,sum(price*num*100) as tfee,sum(oldprice*num*100)as ofee FROM " . tablename('j_hmoney_ordergoods') . " WHERE weid = '".$_W['uniacid']."' and orderid=:a ",array(":a"=>$trade['id']));
	$data=array(
		"order_fee"=>intval($gather['ofee']),
		"total_fee"=>intval($gather['tfee']),
		"num"=>$gather['num1'],
		"species"=>$gather['num2'],
		"status"=>1,
	);
	if($person!=$trade['person']){
		$teafee=($person*intval($table['perperson']*100)+intval($table['teafee']*100));
		$data['person']=$person;
		$data['teafee']=$teafee;
	}
	pdo_update("j_hmoney_order",$data,array("id"=>$orderid));
	//发送信息
	if(count($tempInsertAry)){
		$insertdata=array(
			"shopid"=>$shopid,
			"userid"=>$userid,
			"orderid"=>$orderid,
		);
		if($isallnew){
			$insertdata['mtype']="neworder";
			$insertdata['message']="[".date("m-d H:i")."][".$table['title']."]已下单，下单商品种类".count($newgoodAry)."，请及时处理。";
		}else{
			$insertdata['mtype']="addgood";
			$insertdata['message']="[".date("m-d H:i")."][".$table['title']."]加单，加单商品种类".count($newgoodAry)."，请及时处理。";
		}
		_sendWebMessage($insertdata);
	}
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'finishgood') {
	$mid=intval($_GPC['mid']);
	pdo_update('j_hmoney_ordergoods',array("finishtime"=>TIMESTAMP),array('id'=>$mid));
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'clearorderid') {
	isetcookie('selfttableid', '',-1);
	die(json_encode(array('success'=>true)));
	
} elseif ($operation == 'callsevice') {
	$tid=intval($_GPC['tid']);
	$txt=trim($_GPC['txt']);
	$tablenam=pdo_fetchcolumn("SELECT title FROM " . tablename('j_hmoney_table')." WHERE id=:a ",array(":a"=>$tid));
	$insertdata=array(
		"shopid"=>$shopid,
		"userid"=>$userid,
		"mtype"=>"callsevice",
		"message"=>"[".date("m-d H:i")."][".$tablenam."]呼叫服务员：[".$txt."]",
		"orderid"=>$tid,
		"orderid"=>$orderid,
	);
	_sendWebMessage($insertdata);
	die(json_encode(array('success'=>true,"time"=>TIMESTAMP)));
}
include $this->template($cfg['floder'].'/phone/phone');
